package com.jwdf.uda.ui.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jwdf.uda.R;
import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadListImageResponse;
import com.jwdf.uda.bean.Upload_Picture;
import com.jwdf.uda.event.FollowEvent;
import com.jwdf.uda.event.QuizDetailEvent;
import com.jwdf.uda.http.AHttpTaskService;
import com.jwdf.uda.http.action.AnswerAddAction;
import com.jwdf.uda.http.action.UploadImageListsAction;
import com.jwdf.uda.ui.fragment.question.bean.EditDescribe;
import com.jwdf.uda.ui.fragment.question.bean.NewAnswer;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.DisplayUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ImageProcessing;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.dialog.AlertDialog;
import com.jwdf.uda.view.dialog.ConfirmDialog;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

public class NewAnswerActivity extends AnswerActivity {

    public final long UPLOAD_IMAGE_SIZE_LIMIT = 1024 * 1024;//1M
    private int quesID;
    private File uploadImageFile = null;
    public static void start(Context context, int id, int voteCount, String title) {
        Intent intent = new Intent(context, NewAnswerActivity.class).putExtra(strQuesID, id).putExtra(strVoteCount, voteCount).putExtra(strTitle, title);
        context.startActivity(intent);
    }
    protected void initViews() {
        checkPermission();

        instance = NewAnswer.getInstance();

        quesID = getIntent().getIntExtra(strQuesID, 0);

        // FIXME: 2016/9/23 something usage
        mBinding = DataBindingUtil.setContentView(this, R.layout.lay_new_answer);

        vVoteNone = new View(this);
        vVoteNone.setTag(PbBean.PbSignBaseVoteOptionType.VOTE_OPTION_TYPE_NONE);
        vSel = vVoteNone;


        /** DisplayMetrics获取屏幕信息 */
        final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        screeHeight = displayMetrics.heightPixels;

        ViewTreeObserver vto = mBinding.et.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
                screeWidth = mBinding.et.getMeasuredWidth();
                return true;
            }
        });

        mBinding.et.getLayoutParams().height = DisplayUtils.getDeviceHeight(this) / 7 * 4;

        //getCategoryGet();
        mBinding.et.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
                if((view.getId() == R.id.et && canVerticalScroll(mBinding.et))) {
                    mBinding.et.clearFocus();
                    //mBinding.editDescribe.setFocusable(false);
                    view.getParent().requestDisallowInterceptTouchEvent(true);
                    if(event.getAction() == MotionEvent.ACTION_UP) {
                        view.getParent().requestDisallowInterceptTouchEvent(false);
                        //mBinding.editDescribe.findFocus();
                        //mBinding.editDescribe.setFocusable(true);
                    }
                }
                return false;
            }
        });

        initAnswer();

        findViewById(R.id.vBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        findViewById(R.id.tvHeadOperate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //askForPermission();
                judge();
            }
        });
    }
    protected void onPublished() {

        final PbBean.PbSignBaseVoteOptionType vote = (PbBean.PbSignBaseVoteOptionType) vSel.getTag();
        AnswerAddAction action = new AnswerAddAction(AppContext.getInstance(), quesID, vote, getDescriptionList(), UPLOAD_NEW);
        onNewRequestCall(action.request(new AHttpTaskService.IResCallback<PbBean.PbResQuestionAddAnswer>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAddAnswer> response, PbBean.PbBaseServerInfo baseServerInfo) {
                //closeProgressDialog();

                if(resultCode != 0) {
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_ANSWER_ERROR));
//                    setIsRequest(true);
//                    cancelRequest();
//                    saveImage();
//                    //instance.clearContext();
//                    instance.setmIsUpload(true);
//                    instance.setmDescribe(mBinding.et.getText().toString());
//                    ConfigUtils.setNewAnswer(AppContext.getInstance(), instance);
//                    instance.delete();
                    return;
                }

                Toast.makeText(AppContext.getInstance(), "发表成功", Toast.LENGTH_LONG).show();

                instance.delete();
                ConfigUtils.removeNewAnswer(AppContext.getInstance());
                finish();
                EventBusUtil.post(new QuizDetailEvent(QuizDetailEvent.EVENT_QUIZ_REPLY_ADD));
//                EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_ANSWER_COMPLETE));
                AppBus.getInstance().post(new FollowEvent());
            }
        }));

    }
    private void initAnswer() {
        NewAnswer answer = ConfigUtils.getNewAnswer(this, quesID);
        if(answer != null)
            if(!answer.getmDescribe().equals(""))
                getDraftBoxs(answer.getmDescribe(), answer.getImageList());

        initVote(getIntent().getIntExtra(strVoteCount, 0));
        if(answer != null)
            performClickVote(answer.getVote());
    }

    private void getDraftBoxs(String describe, List<String> imageList) {
        NewAnswer.getInstance().deleteEditDescribeList();
        String content = describe;
        Editable eb = mBinding.et.getEditableText();
        String[] mContent = content.split("￼");

        int startPosition;
        int i = 0;
        /**
         *
         * 获得草稿的图片和文字信息，并把它展示出来
         */
        for(String string : mContent) {
            //LogUtils.d(string);
            EditDescribe editDescribe = new EditDescribe();
            if(!TextUtils.isEmpty(string)) {
                startPosition = mBinding.et.getSelectionStart();
                eb.insert(startPosition, string);
                editDescribe.setDescribe(0);
                editDescribe.setmName(string);
                NewAnswer.getInstance().setEditDescribeList(editDescribe);
            }
            if(i != mContent.length - 1) {
                String mPicPath = imageList.get(i);
                startPosition = mBinding.et.getSelectionStart();
                eb.insert(startPosition, Html.fromHtml("<img src=" + mPicPath + ">", imageGetter, null));
                editDescribe = new EditDescribe();
                editDescribe.setDescribe(1);
                editDescribe.setmUrl(mPicPath);
                NewAnswer.getInstance().setEditDescribeList(editDescribe);
                i++;
            }
        }
    }


    @Override
    public void onBackPressed() {
        UdaUtils.hideInputMethod(this, getCurrentFocus());
        FragmentManager manager = getSupportFragmentManager();
        int count = manager.getBackStackEntryCount();
        if(count == 0) {
            showConfirm();
        } else {
            try {
                manager.popBackStackImmediate();
            } catch(IllegalStateException ignored) {
            }
        }

    }
    private void showConfirm() {
        if(mBinding.et.getText().length() > 0) {
            ConfirmDialog mDraftBoxDialog = new ConfirmDialog(this, "退出新增操作，内容是否要保留?", "不保留", "保留");
            mDraftBoxDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                    ConfigUtils.removeNewAnswer(NewAnswerActivity.this);
                    finish();
                }

                @Override
                public void clickYes() {
                    saveImage();
                    instance.setId(quesID);
                    instance.setmDescribe(mBinding.et.getText().toString());
                    instance.setVote((PbBean.PbSignBaseVoteOptionType) vSel.getTag());
                    ConfigUtils.setNewAnswer(NewAnswerActivity.this, instance);
                    finish();
                }
            });

            mDraftBoxDialog.show();
        } else
            finish();
    }
    public void judge() {
        published();

    }
    public void published() {
//        if(NewAnswer.getInstance().ismIsUpload()) {
            showProgressDialog();
            doUploadAImagesAction();
//        } else {
//            Toast.makeText(this, "上一个任务还没有完成，请等待", Toast.LENGTH_LONG).show();
//        }
    }
    private void doUploadAImagesAction() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                SaveDescribes(mBinding.et.getText().toString(), saveImage());

                if(Commitable()) {
//                    TaskList taskList = new TaskList();
//                    taskList.setType("回答");
//                    taskList.setName(getIntent().getStringExtra(strTitle));
//                    taskList.setmTaskType(UPLOAD_NEW);
//                    LongTask.getInstance().setListList(taskList);
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_SHOW, taskList));
//                    instance.setmIsUpload(false);
                    //instance.setContext(this);
//                    setIsRequest(false);
//                    finish();

                    //List<EditDescribe> list2 = instance.getEditDescribeList();
                    //boolean hasImageAToken = doUploadImagesAction();
                    //if(hasImageAToken) {
                    //    doHasImageTokenSuccess(list2);
                    //}

                    doUploadImagesAction();

                } else {

                    if(isContentLess())
                        toastContentLess();
                    else if(isContentMuch())
                        toastContentMuch();
                }
            }
        });

    }
    private boolean doUploadImagesAction() {
        List<EditDescribe> list2 = instance.getEditDescribeList();
        List<String> listImage = new ArrayList<>();
        for(int i = 0; i < list2.size(); i++)
            if(list2.get(i).getDescribe() == 1)
                listImage.add("file://" + list2.get(i).getmUrl());

        if(listImage.size() == 0) {
            doHasImageTokenSuccess(list2);
        } else {
            ImageCompression(listImage.size(), listImage);
        }

        return true;
    }
    public void ImageCompression(final int pan, final List<String> imageList) {

        List<File> imageFileList = new ArrayList<>(imageList.size());
        for(int i = 0; i < imageList.size(); i++) {
            final int location = i;
            NewAnswer.getInstance().addImageFileList(null, location);
            File imageFile = null;
            try {
                imageFile = new File(new URI(imageList.get(i)));
            } catch(URISyntaxException e) {
                e.printStackTrace();
            }

            if(imageFile.length() > UPLOAD_IMAGE_SIZE_LIMIT) {
                String imageType = ImageProcessing.getImageType(imageFile.getAbsolutePath());
                final String filePath = imageFile.getAbsolutePath();
                try {
                    uploadImageFile = ImageProcessing.createTempImageFile(imageType);//将要保存图片的路径
                } catch(IOException e) {
                    e.printStackTrace();
                }

                Luban.get(AppContext.getInstance()).load(imageFile).putGear(Luban.THIRD_GEAR).setFilename(uploadImageFile.getAbsolutePath()).asObservable().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                }).onErrorResumeNext(new Func1<Throwable, Observable<? extends File>>() {
                    @Override
                    public Observable<? extends File> call(Throwable throwable) {
                        return Observable.empty();
                    }
                }).subscribe(new Action1<File>() {
                    @Override
                    public void call(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        NewAnswer.getInstance().getImageFileList().set(location, file);
                        doImageCompressionSuccess(imageList, pan);
                    }
                });    //启动压缩


            } else {
                NewAnswer.getInstance().getImageFileList().set(location, imageFile);
                doImageCompressionSuccess(imageList, pan);
            }
        }
    }
    //判断图片是否压缩完成
    private void doImageCompressionSuccess(List<String> list, final int pan) {
        List<File> fileList = NewAnswer.getInstance().getImageFileList();
        if(list.size() == NewAnswer.getInstance().getImageFileList().size()) {
            for(int i = 0; i < NewAnswer.getInstance().getImageFileList().size(); i++) {
                if(NewAnswer.getInstance().getImageFileList().get(i) == null) {
                    return;
                }
            }
        } else {
            return;
        }
        doUploadImageAction(pan, NewAnswer.getInstance().getImageFileList());
    }
    private void doUploadImageAction(final int plan, final List<File> imageUrl) {
        UploadImageListsAction action = new UploadImageListsAction(AppContext.getInstance(), imageUrl, UPLOAD_NEW);
        onNewRequestCall(action.request(new UploadImageListsAction.IResCallback<String>() {
            @Override
            public void onCallback(int resultCode, UploadListImageResponse response) {
                //                if(getView() != null) {
                if(resultCode != 0) {
//                    EventBusUtil.post(new LongTaskEvent(LongTaskEvent.LONG_TASK_QUESTION_ERROR));
//                    setIsRequest(true);
//                    cancelRequest();
//                    NewAnswer.getInstance().setmIsUpload(true);
//                    saveImage();
//                    //                        NewAnswer.getInstance().emptyContext();
//                    NewAnswer.getInstance().setmDescribe(mBinding.et.getText().toString());
//                    ConfigUtils.setNewAnswer(AppContext.getInstance(), NewAnswer.getInstance());
//                    NewAnswer.getInstance().delete();
                    return;
                }
                doUploadImageResponse(plan, response);
                //                }
            }
        }));
    }
    private void doUploadImageResponse(int plan, UploadListImageResponse response) {

        Gson gson = new Gson();
        List<String> list = new ArrayList<>();
        for(int i = 0; i < plan; i++) {
            JsonObject a1 = response.getUpload_picture().getAsJsonObject("upload_picture_" + (i + 1) + "");
            java.lang.reflect.Type type = new TypeToken<Upload_Picture>() {}.getType();
            Upload_Picture upload_picture = gson.fromJson(a1, type);
            list.add(upload_picture.getToken());

        }
        //        String aa=upload_picture.getToken();
        int j = 0;
        for(int i = 0; i < instance.getEditDescribeList().size(); i++) {
            if(instance.getEditDescribeList().get(i).getDescribe() == 1) {
                instance.getEditDescribeList().get(i).setToken(list.get(j));
                j = j + 1;
            }
        }


        List<EditDescribe> list2 = instance.getEditDescribeList();

        doHasImageTokenSuccess(list2);
    }
    /**
     * 请求用户给予悬浮窗的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void askForPermission() {
        if(!Settings.canDrawOverlays(this)) {

            final AlertDialog alertDialog = new AlertDialog(this, getString(R.string.permission_denied_msgs), new AlertDialog.CallbackListener() {
                @Override
                public void clickYes() {
                    if(instance.ismIsUpload()) {
                        showProgressDialog();
                        doUploadAImagesAction();
                    } else {
                        Toast.makeText(NewAnswerActivity.this, "上一个任务还没有完成，请等待", Toast.LENGTH_LONG).show();
                    }
                }
            });
            alertDialog.show();

            //            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
            //                    Uri.parse("package:" + getPackageName()));
            //            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        } else {
            //            startService(floatWinIntent);
            if(instance.ismIsUpload()) {
                showProgressDialog();
                doUploadAImagesAction();
            } else {
                Toast.makeText(this, "上一个任务还没有完成，请等待", Toast.LENGTH_LONG).show();
            }

        }
    }

}
